package salesforce;

import java.util.*;

//LC 56 合并区间

/**
 * 1、先排序，按左边位置
 * 2、
 */
public class MergeIntervals {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (i, j) -> i[0] - j[0]);
        Deque<int[]> res = new LinkedList<>();
        res.addLast(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] prev = res.getLast();
            if (intervals[i][0] > prev[1]) {
                // System.out.println(Arrays.toString(prev));
                res.addLast(intervals[i]);
                // System.out.println(Arrays.toString(intervals[i]));
            }else {
                prev[1] = Math.max(intervals[i][1], prev[1]);
            }
        }

        int[][] result = new int[res.size()][2];
        for (int i = 0; i < result.length; i++) {
            result[i] = res.pollFirst();
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] intervals = new int[][]{{2,3},{2,2},{3,3},{1,3},{5,7},{2,2},{4,6}};
        int[][] result = new MergeIntervals().merge(intervals);
        System.out.println(Arrays.deepToString(result));
    }
}
